use std::io::{stdout, Write};

use crossterm::{
    cursor::MoveTo,
    event::{read, Event, KeyEvent, KeyModifiers, KeyCode},
    screen::RawScreen,
    Result,
	execute,
	terminal::{Clear, ClearType},
};

use crossterm::style::{Colorize};

const HELP: &str = r#"Blocking read()
 - Keyboard, mouse and terminal resize events enabled
 - Hit "c" to print current cursor position
 - Use CTRL+F4 to quit
"#;

fn print_events() -> Result<()> {
    loop {
        // Blocking read, is a Event type
        let event = read()?;

        println!("Event::{:?}\r", event);

        if event == Event::Key(KeyCode::Char('c').into()) {
            clear();
			let _ = goto(0, 0);
        }
		
		// 前景色和背景色
		if event == Event::Key(KeyCode::Char('f').into()) {
            println!("{}", "red foreground color\r".red());
			println!("{}", "white foreground color\r".white());
			println!("{}", "green background color\r".on_green());
			println!("{}", "white background color\r".on_white());
        }
		
		if event == Event::Key(KeyCode::Char('m').into()) {
            let _ = goto(0, 0);
        }

        if event == Event::Key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL)) {
			println!("game quit!\r");
            break;
        }
    }

    Ok(())
}

fn goto(x: u16, y: u16) -> Result<()> {
    // Set the cursor to position X: 10, Y: 5 in the terminal
    execute!(stdout(), MoveTo(x, y))?;
    Ok(())
}

fn clear() {
	let _ = execute!(stdout(), Clear(ClearType::All));
}

// 这个Result但是crossterm里对std::result::Result的re-export，具体为：pub type Result<T> = std::result::Result<T, ErrorKind>;
fn main() -> Result<()> {
    println!("{}", HELP);

	// 可以防止Ctrl + C退出，而且这里还不能用_忽略返回值，但是又确实没有哪个地方用到了返回值，好神奇；
	// 如果说不需要忽略Ctrl+C而退出程序，那么这句话可以不加
    let _r = RawScreen::into_raw_mode()?;

    if let Err(e) = print_events() {
        println!("Error: {:?}\r", e);
    }

    Ok(())
}
